import { syncSetTimeout, sendMessage, getMessage, dispatch } from "../../global/tools.js";

export default class PhoneBarHandler {
    static count = 0;
    constructor(webController) {
        PhoneBarHandler.count++;
        if (PhoneBarHandler.count >= 2) {
            alert("collectionPlugin: \nError: PhoneBarHandler.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        this.webController = webController;
        this.config = {
            phonebarstate: {
                old:  "置忙",
                now: "置忙"
            },
            phoneBarElement: {}
        };
        this.init();
    }
    init() {
        // 监听当前状态变化
        {
            const targetElement = document.querySelector(".phonebarstate > p");
            const observer = new MutationObserver((mutationsList) => {
                for (const mutation of mutationsList) {
                    if (mutation.addedNodes.length === 1 && mutation.type === "childList") {
                        if (targetElement.innerText === this.config.phonebarstate.now) return;
                        this.config.phonebarstate.old = this.config.phonebarstate.now;
                        this.config.phonebarstate.now = targetElement.innerText;
                        this.stateChangeSendMessage();
                    }
                }
            });
            const config = { childList: true, subtree: true, characterData: true };
            if (targetElement) {
                observer.observe(targetElement, config);
            } else {
                console.error("collectionPlugin: \nError: PhoneBarHandler.init() -> 获取元素失败。");
                alert("collectionPlugin: \nError: PhoneBarHandler.init() -> 获取元素失败。请刷新页面重试。");
            }
        }
        // 监听消息
        getMessage("aiccyun_phoneBarHandler", message => {
            switch (message.title) {
                case "getPhoneState":
                    sendMessage({
                        from: "aiccyun_phoneBarHandler",
                        to: message.from,
                        toUrl: "https://47.94.82.132:18001/",
                        title: "getPhoneState",
                        data: this.config.phonebarstate
                    });
                    break;
                default:
                    break;
            }
        });
    }
    stateChangeSendMessage() {
        if ($("ul.phonebar").length === 1) {
            this.config.phoneBarElement = $("ul.phonebar")[0];
        }
        sendMessage({
            from: "aiccyun_phoneBarHandler",
            to: "anmi_auto",
            toUrl: "https://47.94.82.132:18001/",
            title: "phoneStateChange",
            data: {
                phoneState: this.config.phonebarstate,
                // phoneBarElement: this.config.phoneBarElement
            }
        });
    }
}